import { getCurrentPermissionList } from '@/api/setting';
import routers from '@/router';
import { useAppStore } from '@/store';


function resolveComponent(name: string) {
  const modules = import.meta.glob('@/views/**/**/*.vue');
  const importPage = modules[`${name}`] as any;
  if (!importPage) {
    console.warn(`Page not found: ${name}`)
  }
  return importPage;
};


export async function initRouterNode(reload: boolean = false) {
  let menuTree: any = []
  const appStore: any = useAppStore();
  if (!appStore.appRoute.length || reload) {
    const res = await getCurrentPermissionList();
    menuTree = res.data.result

  } else {
    menuTree = appStore.appRoute
  }
  const data: any = menuTree
  appStore.updateRoute(menuTree)
  data.forEach((item: any) => {
    routers.addRoute({
      name: item.name,
      path: `/${item.path}`,
      component: () => import('@/layout/default-layout.vue'),
      children: item.children.map((child: any) => {
        return {
          name: child.name,
          path: `/${child.path}`,
          component: resolveComponent(`/src/${child.frontRoute}.vue`),
        };
      }),
    });
  });
}
